<?php
namespace app\home\controller;

use app\home\logic\UsersLogic;
use app\home\model;
use think\Session;

class User extends Base{
    public $user = false;

    public function _initialize(){
        parent::_initialize();
        $this->user = $this->user();
    }

    public function wxinfo(){
        //session('access_token') != '' ?  $access_token = session('access_token') : $access_token = getAccessToken();
        $access_token = getAccessToken();
        $curl = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$access_token.'&openid='.session('openid').'&lang=zh_CN';
        $res = file_get_contents($curl);//返回json数据包
        $result =  json_decode($res, true);
        return $result;
    }

    //注册
    public function register(){
            if (session('openid') == '') $this->getCode();
           // if ($this->user) $this->redirect('Index/index');
            if (IS_AJAX){
                $data = trim_array_element(I('param.'));
                if (!check_mobile($data['phone'])) ajaxReturn(array('status' => 500,'msg' => '请输入正确的手机号码')); //验证手机号码格式
                //用户是否已注册
                $user = M('user')->where(array('phone' => $data['phone']))->find();
               if ($user) ajaxReturn(array('status' => 500,'msg' => '该手机已经注册过了'));
             //   验证短信
                $logic = new UsersLogic();
                $check_code = $logic->check_validate_code($data['code'], $data['phone'], 1);
                if($check_code['status'] != 200){
                    return $check_code;
                }
                //添加用户
                $result = $this->wxinfo();
                if (isset($result['errcode']) && $result['errcode'] == 40003)    ajaxReturn(array('status' => 500,'msg' => 'openid不存在，请先登陆'));
                if (empty($result['openid']))   ajaxReturn(array('status' => 500,'msg' => 'openid不存在，请先登陆1'));
                $map['phone'] = $data['phone']; //手机号码
                $map['password'] = encrypt($data['password']); //密码
                $map['verification'] = encrypt(time().rand(1000,9999)); //登录密钥
                $map['add_time'] = time();
                $map['openid'] = $result['openid']??'123';
                $map['head_img'] = $result['headimgurl']??'123';
                $map['username'] = $result['nickname']??'嘻嘻';
                $map['region'] = $result['city']??'成都';
              //  pr($map);
                $has = M('user')->insertGetId($map);
              //  pr($has,1);
                session('openid',$result['openid']);
                @ajaxReturn(array('status' => 200,'msg' => '注册成功','url' => U('Index/index')));
            }
            $this->assign('title','注册');
            return $this->fetch();

    }

    //登录
    public function login(){
        $type = I('param.type',1);
        if ($type == 2){
            if ($this->user) $this->redirect('Goods/index');
        }else{
            if ($this->user) $this->redirect('Index/index');
        }
        if (IS_AJAX){
            $data = trim_array_element(I('param.'));
            if (!check_mobile($data['phone'])) ajaxReturn(array('status' => 500,'msg' => '请输入正确的手机号码')); //验证手机号码格式
            $user = M('user')->where(array('phone' => $data['phone']))->find();
            if (!$user) ajaxReturn(array('status' => 500,'msg' => '该手机号还未进行注册'));
            $password = encrypt($data['password']);
            if ($password != $user['password']) ajaxReturn(array('status' => 500,'msg' => '密码错误，请重新输入'));
            //$map['verification'] = encrypt(time().rand(1000,9999)); //登录密钥
            //M('user')->where(array('user_id' => $user['user_id']))->save($map);
            session('openid',$user['openid']);
            if ($data['type'] == 2){
                ajaxReturn(array('status' => 200,'msg' => '登录成功','url' => U('Goods/index')));
            }elseif ($data['type'] == 3){
                ajaxReturn(array('status' => 200,'msg' => '登录成功','url' => U('Goods/order_index')));
            }else{
                ajaxReturn(array('status' => 200,'msg' => '登录成功','url' => U('Index/index')));
            }
        }
        $this->assign('type',$type);
        $this->assign('title','登录');
       // pr('111',1);
        return $this->fetch();
    }

    /**
     * 退出登陆
     */
    public function logout(){
        session_unset();
        session_destroy();
        session::clear();
        ajaxReturn(array('status' => 200,'msg' => '退出成功','url' => U('User/login')));
    }

	 //授权登录
    public function wx_login(){
    	$type = I('param.type',1);
        $redirect_uri = urlencode('http://xg.wm61.mingtengnet.com/home/index/get_info_2.html');
        $wx_config = C('wx_config');
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$wx_config['appid'].'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_userinfo&state='.$type.'#wechat_redirect';
        header("Location:".$url);
    }


    //忘记密码
    public function forget(){
        if (IS_AJAX){
            $data = trim_array_element(I('param.'));
            if (!check_mobile($data['phone'])) ajaxReturn(array('status' => 500,'msg' => '请输入正确的手机号码')); //验证手机号码格式
            //用户是否已注册
            $user = M('user')->where(array('phone' => $data['phone']))->find();
            if (!$user) ajaxReturn(array('status' => 500,'msg' => '该手机还未注册'));
            //验证短信
            $logic = new UsersLogic();
            $check_code = $logic->check_validate_code($data['code'], $data['phone'], 2);
            if($check_code['status'] != 200){
                ajaxReturn($check_code);
            }
            if ($data['password'] != $data['password1']) ajaxReturn(array('status' => 500,'msg' => '两次密码输入不一致'));
            $map['password'] = encrypt($data['password']);
            M('user')->where(array('user_id' => $user['user_id']))->save($map);
            session('key','');
            ajaxReturn(array('status' => 200,'msg' => '密码重置成功，请前往登录','url' => U('User/login')));
        }
        $this->assign('title','忘记密码');
        return $this->fetch();
    }

    //个人中心
    public function center(){
        if (!$this->user) $this->redirect('User/login');
        $this->user['head_img'] = head_img($this->user['head_img']);
        $this->user['yhj_count'] = 0; //优惠券数量
        $this->assign('user',$this->user);
        $this->assign('title','个人中心');
        return $this->fetch();
    }

    //个人中心
    public function shop_center(){
        if (!$this->user) $this->redirect('User/login',array('type' => 2));
        $this->user['head_img'] = head_img($this->user['head_img']);
        $this->user['yhj_count'] = 0; //优惠券数量
        $this->assign('user',$this->user);
        $this->assign('title','个人中心');
        return $this->fetch();
    }


    //个人资料
    public function edit_info(){
        if (!$this->user) $this->redirect('User/login');
        $this->user['head_img'] = head_img($this->user['head_img']);
        $this->assign('user',$this->user);
        $this->assign('title','个人资料');
        return $this->fetch();
    }

    //编辑资料
    public function edit_info_do(){
        if (!$this->user) $this->redirect('User/login');
        if (IS_AJAX){
            $data = trim_array_element(I('param.'));
            if ($data['type'] == 1){ //昵称
                M('user')->where(array('user_id' => $this->user['user_id']))->save(array('username' => $data['username']));
            }
            if ($data['type'] == 2){ //性别
                M('user')->where(array('user_id' => $this->user['user_id']))->save(array('sex' => $data['sex']));
            }
            if ($data['type'] == 3){ //年龄
                if (!num($data['year'])) ajaxReturn(array('status' => 500,'msg' => '数据格式填写错误'));
                M('user')->where(array('user_id' => $this->user['user_id']))->save(array('year' => $data['year']));
            }
            if ($data['type'] == 4){ //邮箱
                if (!check_email($data['email'])) ajaxReturn(array('status' => 500,'msg' => '邮箱格式不正确'));
                M('user')->where(array('user_id' => $this->user['user_id']))->save(array('email' => $data['email']));
            }
            if ($data['type'] == 5){ //球龄
                if (!num($data['ball_year'])) ajaxReturn(array('status' => 500,'msg' => '数据格式填写错误'));
                M('user')->where(array('user_id' => $this->user['user_id']))->save(array('ball_year' => $data['ball_year']));
            }
            if ($data['type'] == 6){ //所在地
                if ($data['region'] != '') {
                    M('user')->where(array('user_id' => $this->user['user_id']))->save(array('region' => $data['region']));
                }
            }
            ajaxReturn(array('status' => 200,'msg' => '信息修改成功','url' => U('User/edit_info')));
        }
        $type = I('param.type');
        $region = M('region')->field('name')->where(array('level' => 2))->select();
        $this->assign('regions',$region);
        $this->assign('type',$type);
        $this->assign('user',$this->user);
        $this->assign('title','编辑资料');
        return $this->fetch();
    }

    //我的余额
    public function balance(){
        if (!$this->user) $this->redirect('User/login');
        $this->assign('balance',$this->user['balance']);
        $this->assign('title','我的余额');
        return $this->fetch();
    }

    //我的收货地址
    public function addressList(){
        if (!$this->user) $this->redirect('User/login',array('type' => 2));
        $list = M('user_address')->where(array('user_id' => $this->user['user_id']))->order('is_default desc')->select();
        $this->assign('list',$list);
        $this->assign('title','收货地址');
        return $this->fetch('addressList');
    }

    //添加收货地址
    public function add_address(){
        if (!$this->user) $this->redirect('User/login',array('type' => 2));
        if (IS_AJAX){
            $data = trim_array_element(I('param.'));
            foreach ($data as $key=>$val){
                if (empty($val)){
                    ajaxReturn(array('status' => 500,'msg' => '还有填写项为空'));
                }
            }
            if (!check_mobile($data['phone'])) ajaxReturn(array('status' => 500,'msg' => '手机号码格式不正确'));
            if ($data['is_default'] == 1){
                M('user_address')->where(array('user_id' => $this->user['user_id']))->save(array('is_default' => 0));
            }
            $map['user_id'] = $this->user['user_id'];
            $map['username'] = $data['username'];
            $map['phone'] = $data['phone'];
            $map['postcode'] = $data['postcode'];
            $map['region'] = $data['region'];
            $map['address'] = $data['address'];
            $data['is_default'] != '' ? $map['is_default'] = $data['is_default'] : false;
            if ($data['is_default'] != ''){ //设置为默认地址
                $map['is_default'] = $data['is_default'];
            }else{ //未设置
                //如果是添加的第一条地址，自动设为默认地址
                if (M('user_address')->where(array('user_id' => $this->user['user_id']))->count() == 0){
                    $map['is_default'] = 1;
                }
            }
            M('user_address')->insert($map);
            ajaxReturn(array('status' => 200,'msg' => '添加成功','url' => U('User/addressList')));
        }
        $this->assign('title','添加收货地址');
        return $this->fetch();
    }

    //设置默认切换
    public function tab_default(){
        if (!$this->user) ajaxReturn(array('status' => 401,'msg' => '请先登录后再尝试操作','url' => U('User/login',array('type' => 2))));
        $item_id = I('param.item_id');
        //将所有地址设置成不默认
        M('user_address')->where(array('user_id' => $this->user['user_id']))->save(array('is_default' => 0));
        //设置默认
        M('user_address')->where(array('address_id' => $item_id))->save(array('is_default' => 1));
        ajaxReturn(array('status' => 200,'msg' => '设置成功'));
    }

    //删除地址
    public function del_address(){
        if (!$this->user) ajaxReturn(array('status' => 401,'msg' => '请先登录后再尝试操作','url' => U('User/login',array('type' => 2))));
        $item_id = I('param.item_id');
        $address = M('user_address')->where(array('address_id' => $item_id))->find();
        if (!$address) ajaxReturn(array('status' => 500,'msg' => '500：地址参数错误'));
        if ($address['is_default'] == 1) ajaxReturn(array('status' => 500,'msg' => '该地址为默认地址，无法删除'));
        M('user_address')->where(array('address_id' => $item_id))->delete();
        ajaxReturn(array('status' => 200,'msg' => '删除成功'));
    }

    //编辑收货地址
    public function edit_address(){
        if (!$this->user) $this->redirect('User/login',array('type' => 2));
        if (IS_AJAX){
            $data = trim_array_element(I('param.'));
            foreach ($data as $key=>$val){
                if (empty($val)){
                    ajaxReturn(array('status' => 500,'msg' => '还有填写项为空'));
                }
            }
            if (!check_mobile($data['phone'])) ajaxReturn(array('status' => 500,'msg' => '手机号码格式不正确'));
            $map['username'] = $data['username'];
            $map['phone'] = $data['phone'];
            $map['region'] = $data['region'];
            $map['address'] = $data['address'];
            $map['postcode'] = $data['postcode'];
            if ($data['is_default'] == 1){ //设置该地址为默认
                M('user_address')->where(array('user_id' => $this->user['user_id']))->save(array('is_default' => 0));
                $map['is_default'] = 1;
            }else{ //否
                $address = M('user_address')->where(array('address_id' => $data['address_id']))->find();
                if ($address['is_default'] == 1){
                    $map['is_default'] = 1;
                }
            }
            M('user_address')->where(array('address_id' => $data['address_id']))->save($map);
            ajaxReturn(array('status' => 200,'msg' => '编辑成功','url' => U('User/addressList')));
        }
        $item_id = I('param.item_id');
        $address = M('user_address')->where(array('address_id' => $item_id))->find();
        $this->assign('address',$address);
        $this->assign('title','编辑收货地址');
        return $this->fetch();
    }




    









}